package com.yang.flower.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yang.flower.common.Result;
import com.yang.flower.entity.Comment;
import com.yang.flower.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: CommentController
 * @Author: Yang
 * @DateTime: 2023/2/19 19:06
 **/
@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @PostMapping
    public void save(@RequestBody Comment comment){
        commentService.save(comment);
    }

    @GetMapping("/getByFlowerId/{flowerId}")
    public Result getByFlowerId(@PathVariable("flowerId") Integer flowerId){
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getFlowerId,flowerId);
        List<Comment> commentList = commentService.list(queryWrapper);
        List<Comment> rootComments = commentList.stream().filter(comment -> comment.getPid() == null).collect(Collectors.toList());
        for (Comment rootComment : rootComments) {
            rootComment.setChildren(commentList.stream().filter(comment -> rootComment.getId().equals(comment.getPid())).collect(Collectors.toList()));
        }
        return Result.success(rootComments);
    }

}
